package com.chezai.client.server;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.chezai.client.dao.DaoManager;
import com.chezai.client.dao.manager.TerminalParameterDaoManager;
import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.PreferenceManager;
import com.chezai.client.utils.ToastUtil;
import com.jx.driving.domain.TerminalParameter;
import com.jx.driving.message.TimeTerminalTransmissionMessage;
import com.jx.driving.protocol.terminal.channel.Channel;
import com.jx.driving.request.Terminal0x8105Request;
import com.jx.driving.request.Terminal0x8900Request;
import com.jx.driving.request.domain.TerminalInstruction1;
import com.jx.driving.request.domain.TerminalInstruction2;
import com.jx.driving.response.AbstractResponse;
import com.jx.driving.response.Terminal0x8100Response;
import com.jx.driving.response.Terminal0x8701Response;
import com.jx.driving.response.Terminal0x8702Response;
import com.jx.driving.response.Terminal0x8703Response;
import com.jx.driving.response.Terminal0x8704Response;
import com.jx.driving.response.Terminal0x8705Response;
import com.jx.driving.transmission.Terminal0x0301Transmission;
import com.jx.driving.transmission.Terminal0x0501Transmission;
import com.jx.driving.transmission.Terminal0x0502Transmission;
import com.jx.driving.transmission.Terminal0x0503Transmission;
import com.jx.driving.transmission.Terminal0x8101Transmission;
import com.jx.driving.transmission.Terminal0x8102Transmission;
import com.jx.driving.transmission.Terminal0x8201Transmission;
import com.jx.driving.transmission.Terminal0x8202Transmission;
import com.jx.driving.transmission.Terminal0x8301Transmission;
import com.jx.driving.transmission.Terminal0x8401Transmission;
import com.jx.driving.transmission.Terminal0x8402Transmission;
import com.jx.driving.transmission.Terminal0x8501Transmission;
import com.jx.driving.transmission.Terminal0x8502Transmission;
import com.jx.driving.transmission.Terminal0x8503Transmission;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;


/**
 * 协议接收监听接口实现类
 * Created by likunyang on 2017/8/24.
 */

public class ChannelListenerImpl implements ChannelListener {
    private static final int AUTH_SUCESS = 0;
    private static final int AUTH_FAILED = 1;
    private CustomHandler customHandler;
    private TransmissionMessageUtil messageUtil;

    ChannelListenerImpl() {
        customHandler = new CustomHandler(Looper.getMainLooper());
        messageUtil = new TransmissionMessageUtil();
    }

    @Override
    public void active(Channel c) {
        EventBus.getDefault().postSticky(Const.CHANNEL_ACTIVE);
        if (PreferenceManager.isRegister()) {
            TerminalSocketClientManager.getInstance().authenTicate();
        }
    }

    @Override
    public void inactive(Channel c) {
        EventBus.getDefault().postSticky(Const.CHANNEL_INACTIVE);
        customHandler.sendEmptyMessage(Const.CHANNEL_INACTIVE);
        TerminalSocketClientManager.getInstance().setAuthenticated(false);
    }

    @Override
    public void onReceive(Channel c, Object msg) {
        Logger.t("Response").d(msg.toString());
        //服务器端返回通用应答
        if (msg instanceof AbstractResponse) {
            AbstractResponse abstractResponse = (AbstractResponse) msg;
            int msgId = abstractResponse.getId();
            switch (msgId) {
                case 0x0102://终端鉴权
                    if (abstractResponse.getResult() == 0) {
                        TerminalSocketClientManager.getInstance().setAuthenticated(true);
                        customHandler.sendEmptyMessage(AUTH_SUCESS);
                    } else {
                        TerminalSocketClientManager.getInstance().setAuthenticated(false);
                        customHandler.sendEmptyMessage(AUTH_FAILED);
                    }
                    break;
                case 0x0002: //心跳包
                    break;
                default:
                    EventBus.getDefault().post(abstractResponse);
                    break;
            }
        } else if (msg instanceof Terminal0x8900Request) {
            //数据下行透传，通道应答
            TimeTerminalTransmissionMessage realMessage = messageUtil.getTimeTerminalTransmissionMessage((Terminal0x8900Request) msg);
            if (realMessage instanceof Terminal0x8101Transmission) {
                Terminal0x8101Transmission ox8101 = (Terminal0x8101Transmission) realMessage;
                EventBus.getDefault().post(ox8101);
            } else if (realMessage instanceof Terminal0x8102Transmission) {
                Terminal0x8102Transmission ox8102 = (Terminal0x8102Transmission) realMessage;
                EventBus.getDefault().post(ox8102);
            } else if (realMessage instanceof Terminal0x8201Transmission) {
                Terminal0x8201Transmission ox8201 = (Terminal0x8201Transmission) realMessage;
                EventBus.getDefault().post(ox8201);
            } else if (realMessage instanceof Terminal0x8202Transmission) {
                Terminal0x8202Transmission ox8202 = (Terminal0x8202Transmission) realMessage;
                EventBus.getDefault().post(ox8202);
            } else if (realMessage instanceof Terminal0x8301Transmission) {
                if (!Const.IS_TRAINING) return;
                //4.2.3.1 立即拍照
                int uploadType = ((Terminal0x8301Transmission) realMessage).getUploadType();
                int size = ((Terminal0x8301Transmission) realMessage).getSize();
                int cameraChannel = ((Terminal0x8301Transmission) realMessage).getCameraChannel();
                //1：可以拍摄； 2：拍照失败； 3：SD 卡故障； 4：正在拍照，不能执行；
                // 5：重新连接摄像头，不能保证拍照； 6：正在上传查询照片，不能执行 9：其他错误
                Terminal0x0301Transmission ox0301 = new Terminal0x0301Transmission();
                if (Const.isTakePhoto) {
                    ox0301.setResult((short) 4);
                } else {
                    ox0301.setResult((short) 1);
                }
                ox0301.setUploadType((short) uploadType);
                ox0301.setSize((short) size);
                ox0301.setCameraChannel((short) cameraChannel);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth((messageUtil.buildTerminal0x0900Request(ox0301, false, false)));
                //如果正在上传图片不能拍照
                if (!Const.isTakePhoto) {
                    Const.isTakePhoto = true;
                    //uploadType 1：拍摄完成后自动请求上传；2：拍摄完成后存储在本地；255：停止拍摄并上传图片
                    EventBus.getDefault().post(ox0301);
                }
            } else if (realMessage instanceof Terminal0x8401Transmission) {
                Terminal0x8401Transmission ox8401 = (Terminal0x8401Transmission) realMessage;
                EventBus.getDefault().post(ox8401);
            } else if (realMessage instanceof Terminal0x8402Transmission) {
                Terminal0x8402Transmission ox8402 = (Terminal0x8402Transmission) realMessage;
                EventBus.getDefault().post(ox8402);
            } else if (realMessage instanceof Terminal0x8501Transmission) {//设置终端应用参数
                Terminal0x8501Transmission ox8501 = (Terminal0x8501Transmission) realMessage;
                TerminalParameter terminalParameter = ox8501.getParameter();
                TerminalParameterDaoManager instance = TerminalParameterDaoManager.getInstance();
                instance.updateTerminalParameterWith0x8501(terminalParameter);
                Terminal0x0501Transmission req = new Terminal0x0501Transmission();
                //1：设置成功；2：设置失败；9：其他错误
                req.setResult((short) 1);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(req, false, false));
            } else if (realMessage instanceof Terminal0x8502Transmission) {
                //设置禁训状态 1：可用  2：禁用
                Terminal0x8502Transmission ox8502 = (Terminal0x8502Transmission) realMessage;
                short canUse = ox8502.getStatus();
                String workMsg = new String(ox8502.getReminder());
                if (canUse == 1) {
                    PreferenceManager.putLong(Const.SP_POWER_TIME, System.currentTimeMillis());
                }
                PreferenceManager.putBoolean(Const.SP_IS_PROHIBIT_TRAIN, canUse == 2);
                PreferenceManager.putString(Const.SP_PROHIBIT_MSG, workMsg);
                Terminal0x0502Transmission req = new Terminal0x0502Transmission();
                //0：默认应答；1：设置成功；2：设置失败；9：其他错误
                req.setResult((short) 1);
                boolean state = PreferenceManager.getBoolean(Const.SP_IS_PROHIBIT_TRAIN, false);
                String saveWorkMsg = PreferenceManager.getString(Const.SP_PROHIBIT_MSG, "");
                if (state) {
                    req.setStatus((short) 2);
                } else {
                    req.setStatus((short) 1);
                }
                req.setReminder(saveWorkMsg.getBytes());
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(req, false, false));
            } else if (realMessage instanceof Terminal0x8503Transmission) {//查询终端参数
                Terminal0x0503Transmission req = new Terminal0x0503Transmission();
                com.jx.driving.domain.TerminalParameter terminalParameter = TerminalParameterDaoManager.getInstance().findTerminalParameter(com.chezai.client.bean.TerminalParameter.APP_PARAM);
                req.setParameter(terminalParameter);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(req, false, false));
            }
        } else {
            if (msg instanceof Terminal0x8100Response) {
                //设备注册应答
                Terminal0x8100Response ox8100 = (Terminal0x8100Response) msg;
                EventBus.getDefault().post(ox8100);
            } else if (msg instanceof Terminal0x8105Request) {
                //终端控制对应事件处理
                Terminal0x8105Request ox8105 = (Terminal0x8105Request) msg;
                int cmd = ox8105.getCmd();
                switch (cmd) {
                    case Const.ControlEvent.APP_UPDATA:
                        TerminalInstruction1 terminalInstru = (TerminalInstruction1) ox8105.getInstruction();
                        if (null != terminalInstru) {
                            String url = terminalInstru.getUrl();
                            if (TextUtils.isEmpty(url) || !url.endsWith(".apk")) {
                                return;
                            }
                            Intent intent = new Intent(Const.UPDATE_APP);
                            intent.putExtra("url", url);
                            TerminalApplication.getTerminalContext().sendBroadcast(intent);
                        }
                        break;
                    case Const.ControlEvent.CONNET_SERVER:
                        //链接指定服务器
                        TerminalInstruction2 obj = (TerminalInstruction2) ox8105.getInstruction();
                        TerminalSocketClientManager.getInstance().changeServerAddress(obj.getIpAddress(), obj.getTcpPort(), obj.getServerConnectionTime(), obj.getConnectionOrder());
                        break;
                    case Const.ControlEvent.TERMINAL_RESET:
                        try {
                            DeviceUtils.restartAPP(TerminalApplication.mContext);
                        } catch (Exception e) {
                        }
                        break;
                    case Const.ControlEvent.TERMINAL_RESET_SETTING:
                        try {
                            DaoManager.getInstance().deleAllData();
                            PreferenceManager.clear();
                            TerminalSocketClientManager.getInstance().stopSendHead();
                            DeviceUtils.restartAPP(TerminalApplication.mContext);
                        } catch (Exception e) {
                        }
                        break;
                }
            } else if (msg instanceof Terminal0x8701Response) {
                //设备基础信息应答
                Terminal0x8701Response ox8701 = (Terminal0x8701Response) msg;
                EventBus.getDefault().postSticky(ox8701);
            } else if (msg instanceof Terminal0x8702Response) {
                //服务器下发学员、教练身份信息
                Terminal0x8702Response ox8702 = (Terminal0x8702Response) msg;
                EventBus.getDefault().post(ox8702);
            } else if (msg instanceof Terminal0x8703Response) {
                //根据用户身份、统一编号、查询用户信息
                Terminal0x8703Response ox8703 = (Terminal0x8703Response) msg;
                EventBus.getDefault().post(ox8703);
            } else if (msg instanceof Terminal0x8704Response) {
                Terminal0x8704Response ox8704 = (Terminal0x8704Response) msg;
                EventBus.getDefault().post(ox8704);
            }else if (msg instanceof Terminal0x8705Response) {
                Terminal0x8705Response ox8705 = (Terminal0x8705Response) msg;
                EventBus.getDefault().post(ox8705);
            }
        }
    }


    class CustomHandler extends Handler {
        CustomHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AUTH_SUCESS:
                    ToastUtil.showToast(TerminalApplication.getTerminalContext(), "鉴权成功！");
                    break;
                case AUTH_FAILED:
                    ToastUtil.showToast(TerminalApplication.getTerminalContext(), "鉴权失败请重试");
                    break;
                case Const.CHANNEL_INACTIVE:
                    ToastUtil.showToast(TerminalApplication.getTerminalContext(), "与服务器断开连接");
                    break;
            }
        }
    }
}
